<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\User;
use App\Notifications\EmailVerificationNotification;
use Cache;
use Exception;
use Illuminate\Http\Request;

class EmailVerificationController extends Controller
{
    /**
     * 处理邮箱验证
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws Exception
     */
    public function verify(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'token' => 'required',
        ]);

        $email = $request->input('email');
        $token = $request->input('token');
        $key = 'email_verification_'.$email;

        if ($token != Cache::get($key)){
            throw new InvalidRequestException('验证链接不正确或已过期');
        }

        if (!$user = User::where('email', $email)->first()){
            throw new InvalidRequestException('用户不存在');
        }

        if ($user->email_verified){
            throw new InvalidRequestException('你已经验证过邮箱了');
        }

        // 删除缓存，修改邮箱验证状态
        Cache::forget($key);
        $user->update(['email_verified' => true]);
        return view('pages.success', ['msg' => '邮箱验证成功']);
    }

    /**
     * 发送验证邮箱邮件
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws Exception
     */
    public function send(Request $request)
    {
        $user = $request->user();
        if ($user->email_verified){
            throw new InvalidRequestException('你已经验证过邮箱了');
        }

        $user->notify(new EmailVerificationNotification());
        return view('pages.success', ['msg' => '邮件发送成功']);
    }
}
